package com.qq.servlet;

import java.io.File;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qq.bean.Users;
import com.qq.service.UsersService;
import com.qq.service.impl.UsersServiceImpl;

@MultipartConfig
@WebServlet("/updateavatarImg.do")
public class UpdateUserAvatarServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		Users user = (Users)req.getSession().getAttribute("loginUsers");
		Part part = req.getPart("inputImg");
		//唯一名字
		String name = UUID.randomUUID()+part.getSubmittedFileName();
		//真实路径
		String realPath = "c:/qq/headImgs/"+name; 
		//访问路径
		String visitPath = "/chatBlog/qq/headImgs/"+ name;
		UsersService userService = new UsersServiceImpl();
		int isUpdate = userService.updateUsersAvatar(user.getAccount(), visitPath);
		user.setAvatar(visitPath);
		ObjectMapper om = new ObjectMapper();
		resp.setContentType("application/json;charset=utf-8");
		
		if(isUpdate==1) {
			File file = new File(user.getAvatar());
			if(file.exists()) {
				file.delete();
			}
			part.write(realPath);
			om.writeValue(resp.getWriter(), true);
		}else {
			om.writeValue(resp.getWriter(), false);
		}
	}
}
